package ReflectDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//通过反射获得类的信息
public class Test10 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
        Class c1 = Class.forName("ReflectDemo.User");

        //获得类的名字
        System.out.println(c1.getName());  //获得包名 + 类名
        System.out.println(c1.getSimpleName());  //获得类名

        //获得类的属性
        System.out.println("========");
        Field[] fields = c1.getFields();  //只能找到public属性
        for (Field field : fields) {
            System.out.println(field);
        }

        fields = c1.getDeclaredFields();  //找到全部的属性,包括私有属性
        for (Field field : fields) {
            System.out.println(field);
        }

        //获得类的方法
        System.out.println("========");
        Method[] methods = c1.getMethods();  //获得本类及其父类的全部public方法
        for (Method method : methods) {
            System.out.println("getMethods : " + method);
        }

        methods = c1.getDeclaredMethods();  //获得本类的所有方法
        for (Method method : methods) {
            System.out.println("getDeclaredMethods : " + method);
        }

        //获得指定方法  (需要传递参数类型,方便有方法重载时定位方法)

        Method getName = c1.getMethod("getName",null);
        Method setName = c1.getMethod("setName",String.class);

        System.out.println(getName);
        System.out.println(setName);

        //获得构造器
        System.out.println("========");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("getConstructors : " + constructor);
        }

        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("getDeclaredConstructors : " + constructor);
        }

        //获得指定的构造器
        Constructor declaredConstructor = c1.getDeclaredConstructor(int.class,String.class );
        System.out.println(declaredConstructor);

    }
}
